# -*- coding: utf-8 -*-
"""Public section, including homepage and signup."""
from flask import (
    Blueprint,
    current_app,
    flash,
    redirect,
    render_template,
    request,
    url_for,
)
from flask_login import login_required, login_user, logout_user

from myproject.extensions import login_manager
from myproject.public.forms import LoginForm
from myproject.user.forms import RegisterForm
from myproject.user.models import User
from myproject.utils import flash_errors

blueprint = Blueprint("public", __name__, static_folder="../static")


@login_manager.user_loader
def load_user(user_id):
    """Load user by ID."""
    return User.get_by_id(int(user_id))


@blueprint.route("/", methods=["GET", "POST"])
def home():
    """Home page."""
    form = LoginForm(request.form)
    current_app.logger.info("Hello from the home page!")
    # Handle logging in
    if request.method == "POST":
        if form.validate_on_submit():
            login_user(form.user)
            flash("You are logged in.", "success")
            redirect_url = request.args.get("next") or url_for("user.members")
            return redirect(redirect_url)
        else:
            flash_errors(form)
    return render_template("public/home.html", form=form)


@blueprint.route("/logout/")
@login_required
def logout():
    """Logout."""
    logout_user()
    flash("You are logged out.", "info")
    return redirect(url_for("public.home"))


@blueprint.route("/register/", methods=["GET", "POST"])
def register():
    """Register new user."""
    form = RegisterForm(request.form)
    if form.validate_on_submit():
        User.create(
            username=form.username.data,
            email=form.email.data,
            password=form.password.data,
            active=True,
        )
        flash("Thank you for registering. You can now log in.", "success")
        return redirect(url_for("public.home"))
    else:
        flash_errors(form)
    return render_template("public/register.html", form=form)


@blueprint.route("/about/")
def about():
    """About page."""
    form = LoginForm(request.form)
    return render_template("public/about.html", form=form)



from myproject.extensions import openai_client
from myproject.public.forms import AskForm

@blueprint.route('/ask/', methods=['GET', 'POST'])
@login_required
def ask():
    form = AskForm(request.form)
    response_text = None  # 初始化变量以存储API响应文本
    
    if form.validate_on_submit():
        question = form.askbox.data
        
        try:
            response = openai_client.ask(question)  # 发送请求到OpenAI API
            response_text = response  # 获取响应文本
            current_app.logger.info(f"问题已提交: {question}, 收到的回答: {response}")
            flash("您的问题已成功提交！", "success")
        except Exception as e:
            current_app.logger.error(f"OpenAI API调用失败: {e}")
            flash("很抱歉，我们暂时无法处理您的问题，请稍后再试。", "error")
            # 发生错误时，仍然需要返回模板，但不显示回答
            return render_template('public/ask.html', form=form, response_text=None)
            
    # 对于GET请求或表单验证未通过的情况，显示提问表单
    # 对于POST请求且表单验证通过的情况，显示提问表单及回答
    return render_template('public/ask.html', form=form, response_text=response_text)


# chat
from myproject.extensions import openai_chat_client
from myproject.public.forms import ChatAskForm


@blueprint.route('/chatask/', methods=['GET', 'POST'])
@login_required
def chatask():
    form = ChatAskForm()
    response_text = None
    messages = []

    if form.validate_on_submit():
        question = form.chataskbox.data
        try:
            response_text, messages = openai_chat_client.ask(question)
        except Exception as e:
            print(f"调用OpenAI API时出错: {e}")
            # 错误信息反馈给用户
            response_text = "抱歉，处理您的请求时出现了问题。"

    # 无论是POST还是GET请求，都会执行同一个render_template调用
    return render_template('public/chatask.html', form=form, response_text=response_text, messages=messages)
